import { Injectable } from '@nestjs/common';
import { Video } from './entity/video/video.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { IsNull, Not, Repository } from 'typeorm';
import utils from './common/utils';
import { OriginalEnum, VideoEnum } from './entity/video/video.enum';
import { InternetCelebrityGroup } from './entity/internetCelebrityGroup/internetCelebrityGroup.entity';
import { WxUser } from './entity/wxUser/wxUser.entity';

@Injectable()
export class AppService {

  constructor(
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    @InjectRepository(InternetCelebrityGroup)
    private internetCelebrityGroupRespository: Repository<InternetCelebrityGroup>,
    @InjectRepository(WxUser)
    private wxUserRespository: Repository<WxUser>
  ){

  }

  getHello(): string {
    return 'Hello World!';
  }

  getIDCard(works, list){
    let id = ''
    let loop = async () => {
      //作品 A12345
      if(works){
        id = utils.randomStringID(1, 5, true)
      }else{
        //问题 12345A
        id = utils.randomStringID(1, 5)
      }
      if(list.find(e => e.id_card == id)){
        loop()
      }
    }
    loop()
    return id
  }

  async updateVideoIdCard(){
    let list = await this.videoRepository.find({where:{id_card:IsNull()}})
    list.map(item => {
      item.id_card = this.getIDCard(item.original === OriginalEnum.yes, list)
    })
    let sql = []
    list.map(e => {
      sql.push(`update video set id_card = '${e.id_card}' where id = ${e.id}`)
    })
    console.log(list.map(e => ({id:e.id,id_card:e.id_card})))
    return sql.join(';')
  }


  getIDCard_IcGroup(list){
    let id = ''
    let loop = async () => {
      id = utils.randomNumberID(7)
      if(list.find(e => e.id_card == id)){
        loop()
      }
    }
    loop()
    return id
  }


  async updateIcGroupIdCard(){
    let list = await this.internetCelebrityGroupRespository.find({where:{id_card:IsNull()}})
    list.map(item => {
      item.id_card = this.getIDCard_IcGroup(list)
    })
    let sql = []
    list.map(e => {
      sql.push(`update internet_celebrity_group set id_card = '${e.id_card}' where id = ${e.id}`)
    })
    console.log(list.map(e => ({id:e.id,id_card:e.id_card})))
    return sql.join(';')
  }

  getIDCard_WxUser(list){
    let id = ''
    let loop = async () => {
      id = utils.randomNumberID(6)
      if(list.find(e => e.id_card == id)){
        loop()
      }
    }
    loop()
    return id
  }

  async updateWxUserIdCard(){
    let list = await this.wxUserRespository.find({where:{id_card:IsNull()}})
    list.map(item => {
      item.id_card = this.getIDCard_WxUser(list)
    })
    let sql = []
    list.map(e => {
      sql.push(`update wx_user set id_card = '${e.id_card}' where id = ${e.id}`)
    })
    console.log(list.map(e => ({id:e.id,id_card:e.id_card})))
    return sql.join(';')
  }

}
